package cn.schoolwow.workflow.module.definition.query.service;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.workflow.domain.instance.ManualWorkFlowAssigner;
import cn.schoolwow.workflow.domain.task.WorkFlowAssigner;
import cn.schoolwow.workflow.entity.WorkFlowDefinition;
import cn.schoolwow.workflow.entity.WorkFlowNode;
import com.alibaba.fastjson.JSONArray;

import java.util.ArrayList;
import java.util.List;

public class GetManualWorkFlowAssignerListServiceFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        String definitionName = flowContext.checkData("definitionName", String.class);
        DAO dao = flowContext.checkInstanceData(DAO.class);

        List<WorkFlowNode> workFlowNodeList = dao.query(WorkFlowNode.class)
                .joinTable(WorkFlowDefinition.class, "definition_id", "id")
                .addQuery("name", definitionName)
                .done()
                .execute()
                .getList();

        List<ManualWorkFlowAssigner> manualWorkFlowAssignerList = new ArrayList<>();
        for(WorkFlowNode workFlowNode:workFlowNodeList){
            JSONArray array = workFlowNode.getAssigner();
            if(null==array||array.isEmpty()){
                continue;
            }
            List<WorkFlowAssigner> workFlowAssignerList = array.toJavaList(WorkFlowAssigner.class);
            for(int i=0;i<workFlowAssignerList.size();i++){
                WorkFlowAssigner workFlowAssigner = workFlowAssignerList.get(i);

                switch (workFlowAssigner.assigneeType){
                    case 1:{
                        ManualWorkFlowAssigner manualWorkFlowAssigner = new ManualWorkFlowAssigner();
                        manualWorkFlowAssigner.nodeName = workFlowNode.getName();
                        manualWorkFlowAssigner.assignerGroupIndex = i;
                        manualWorkFlowAssignerList.add(manualWorkFlowAssigner);
                    }break;
                }
            }
        }
        flowContext.putTemporaryData("manualWorkFlowAssignerList", manualWorkFlowAssignerList);
    }

    @Override
    public String name() {
        return "获取流程定义中的发起人自选审批人列表服务流程";
    }

}
